package com.Servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 动态验证码
 */
@WebServlet(name = "com.Servlet.VerifyCodeServlet",urlPatterns = "/VerifyCode.do")
public class VerifyCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //高和低
        int height =40;
        int width=80;
        String data="abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

//        随机数
        Random random = new Random();
        //2、创建一个图片
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //3、画板
        Graphics graphics = image.getGraphics();
        //4、填充矩形
        graphics.setColor(Color.BLACK);//黑色
        graphics.fillRect(0,0,width,height);//设置宽高
        graphics.setColor(Color.WHITE);//填充白色
        graphics.fillRect(1,1,width,height);//里面的长高
        //设置字体 宋体 粗体 斜体 字体大小20
        graphics.setFont(new Font("宋体",Font.BOLD|Font.ITALIC,20));
        //5、写随机数
        for (int i=0;i<4;i++){
            //设置颜色
            graphics.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            //获得随机数
            int index = random.nextInt(data.length());
            //切割随机数
            String str = data.substring(index,index+1);
            //将字等分
            graphics.drawString(str,width/6 *(i+1),20);

        }
        //画干扰线
        for (int i= 0;i<3;i++){
            //绘制颜色
            graphics.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            //设置随机线
            graphics.drawLine(random.nextInt(width),random.nextInt(height),random.nextInt(width),random.nextInt(height));
            //随机点
            graphics.drawOval(random.nextInt(width),random.nextInt(height),2,2);

        }
        //将图片响应给浏览器
        ImageIO.write(image,"jpg",response.getOutputStream());
    }
}
